#!/usr/bin/env python3

import argparse
import os

import common

container_name = common.repo_short_id
container_hostname = common.repo_short_id
image_name = common.repo_short_id
target_dir = '/root/{}'.format(common.repo_short_id)
docker = ['sudo', 'docker']
def create(args):
    common.run_cmd(docker + ['build', '-t', image_name, '.', common.Newline])
    # --privileged for KVM:
    # https://stackoverflow.com/questions/48422001/launching-qemu-kvm-from-inside-docker-container
    common.run_cmd(
        docker +
        [
            'create', common.Newline,
            '--hostname', container_hostname, common.Newline,
            '-i', common.Newline,
            '--name', container_name, common.Newline,
            '--net', 'host', common.Newline,
            '--privileged', common.Newline,
            '-t', common.Newline,
            '-w', target_dir, common.Newline,
            '-v', '{}:{}'.format(os.getcwd(), target_dir), common.Newline,
            image_name,
        ]
    )
def destroy(args):
    stop(args)
    common.run_cmd(docker + ['rm', container_name, common.Newline])
    common.run_cmd(docker + ['rmi', image_name, common.Newline])
def sh(args):
    start(args)
    if args:
        sh_args = args
    else:
        sh_args = ['bash']
    common.run_cmd(
        docker + ['exec', '-i', '-t', container_name] +
        sh_args +
        [common.Newline],
    )
def start(args):
    common.run_cmd(docker + ['start', container_name, common.Newline])
def stop(args):
    common.run_cmd(docker + ['stop', container_name, common.Newline])
cmd_action_map = {
    'create': lambda args: create(args),
    'DESTROY': lambda args: destroy(args),
    'sh': lambda args: sh(args),
    'start': lambda args: start(args),
    'stop': lambda args: stop(args),
}
parser = argparse.ArgumentParser()
parser.add_argument('cmd', choices=cmd_action_map)
parser.add_argument('args', nargs='*')
common.add_dry_run_argument(parser)
args = parser.parse_args()
common.setup_dry_run_arguments(args)
cmd_action_map[args.cmd](args.args)
